package com.rk.kbk.controller;

import com.rk.kbk.common.FailException;
import com.rk.kbk.common.JsonResp;
import com.rk.kbk.common.OrderUtils;
import com.rk.kbk.dao.*;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.*;
import com.rk.kbk.service.UserService;
import com.rk.kbk.sms.SmsUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @SellerWithdrawController
 * @Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/sellerWithdraw")
public class SellerWithdrawController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private SellerWithdrawDao sellerWithdrawDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CashRecordDao cashRecordDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private WithdrawSettingDao withdrawSettingDao;
    @Autowired
    private WithdrawMesgDao withdrawMesgDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改
     * @param sellerWithdraw
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSellerWithdraw",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSellerWithdraw(@RequestBody SellerWithdraw sellerWithdraw){
        log.debug("添加/修改");
        sellerWithdrawDao.save(sellerWithdraw);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改
     * @param sellerWithdraws
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeSellerWithdraw",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeSellerWithdraw(@RequestBody List<SellerWithdraw> sellerWithdraws){
        log.debug("批量添加/修改");
        sellerWithdrawDao.save(sellerWithdraws);
        return JsonResp.ok();
    }

    /**
     * @获取详情-BySellerWithdrawId
     * @param sellerWithdrawId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sellerWithdrawDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findSellerWithdrawDetailsBySellerWithdrawId(Long sellerWithdrawId) {
        log.debug("获取详情-BySellerWithdrawId");
        return JsonResp.ok(sellerWithdrawDao.findOne(sellerWithdrawId));
    }

    /**
     * @分页查询(jpa方式)
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageSellerWithdrawJpa( Integer pageNum, Integer pageSize,Integer userType,String search ) {
        log.debug("分页查询(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        page = sellerWithdrawDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    //找出所有审核中的提现记录
                    expressions.add(cb.equal(root.get("status"), "1"));
                    //下拉框
                    List<User> users;
                    if(userType==0){
                         users = userDao.findAll();
                    }else{
                         users = userDao.findByUserType(userType);
                    }
                    List<Long> ids = users.stream().map(User::getId).collect(Collectors.toList());
                    //in
                    CriteriaBuilder.In<Object> stick = cb.in(root.get("user"));
                    for (Long l1 : ids) {
                        expressions.add(stick.value(l1));
                    }

                    //模糊查询
                    List<User> users1 = userDao.findByPhoneLike("%"+search+"%");
                    List<Long> ids1 = users.stream().map(User::getId).collect(Collectors.toList());
                    if(users1!=null&&!users1.isEmpty()){
                        CriteriaBuilder.In<Object> stick1 = cb.in(root.get("user"));
                        for (Long l2 : ids1) {
                            expressions.add(stick1.value(l2));
                        }
                    }else{
                        CriteriaBuilder.In<Object> stick1 = cb.in(root.get("user"));
                        expressions.add(stick1.value(0));
                    }
                    return predicate;
                }, pageable);
//        List<SellerWithdraw> content = page.getContent();
//        for (SellerWithdraw sellerWithdraw1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @设置审核成功
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/setPass",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp setPass(Long id) throws Exception {
        log.debug("设置审核成功");
        SellerWithdraw sellerWithdraw =sellerWithdrawDao.findOne(id);
        User user=sellerWithdraw.getUser();
        WithdrawMesg withdrawMesg=sellerWithdraw.getWithdrawMesg();
        Integer type=sellerWithdraw.getWithdrawType();
        Account account=accountDao.findByUser(user);
        Double allMoney=account.getAllMoney();//余额
        Double depositMoney=account.getDepositMoney();//押金
        String title="";
        if(type==1){//余额提现
            /*if(allMoney.compareTo(sellerWithdraw.getDrawPrice())<0){
                return JsonResp.fa("余额不足");
            }else {
                account.setAllMoney(new BigDecimal(allMoney).subtract(new BigDecimal(sellerWithdraw.getDrawPrice())).doubleValue());
            }*/
            title="余额提现（已完成）";
        }else if(type==2){//押金提现
            if(depositMoney.compareTo(sellerWithdraw.getDrawPrice())<0){
                return JsonResp.fa("押金不足");
            }/*else {
                account.setDepositMoney(new BigDecimal(depositMoney).subtract(new BigDecimal(sellerWithdraw.getDrawPrice())).doubleValue());
            }*/
            title="押金提现";
        }
        //-----------------------------------钱包余额记录----------------------
//        CashRecord cashRecord=new CashRecord();
//        cashRecord.setUser(sellerWithdraw.getUser());
//        cashRecord.setTitle(title);
//        cashRecord.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他、4保险
//        cashRecord.setRecoedType(2);//提现
//        if(sellerWithdraw.getWithdrawType()==1){
//            cashRecord.setMoneyType(1);
//            cashRecord.setPayType(1);//余额支付
//        }else  if(sellerWithdraw.getWithdrawType()==2){
//            cashRecord.setMoneyType(2);
//            cashRecord.setPayType(4);//押金支付
//        }
//        cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
//        cashRecord.setMoney(sellerWithdraw.getDrawPrice());
//        cashRecord.setStatus(null);//提现
//        cashRecord.setGivePerson(2);
//        cashRecord.setReceivePerson(2);
//        cashRecord.setWithdrawStatus(2);//提现状态:默认1申请中,2已打款,3失败
//        cashRecord.setBankCard(withdrawMesg.getBankNum()); //银行卡号
//        cashRecord.setBankName(withdrawMesg.getBankName());//开户行
//        cashRecord.setBankCardName(withdrawMesg.getRealName());//持卡人姓名
//        cashRecordDao.save(cashRecord);
        sellerWithdraw.setStatus(2);
        sellerWithdrawDao.save(sellerWithdraw);
        return JsonResp.ok();
    }

    /**
     * @设置审核失败
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/setFail",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp setFail(Long id) throws Exception {
        log.debug("设置审核失败");
        SellerWithdraw sellerWithdraw =sellerWithdrawDao.findOne(id);
        WithdrawMesg withdrawMesg=sellerWithdraw.getWithdrawMesg();
        //--------------------------退钱-------------------------
        User user=sellerWithdraw.getUser();
        Account account=accountDao.findByUser(user);
        account.setAllMoney(new BigDecimal(String.valueOf(account.getAllMoney())).add(new BigDecimal(String.valueOf(sellerWithdraw.getDrawPrice()))).doubleValue());
        accountDao.save(account);

        //-----------------钱包提现记录--------------------------------
        CashRecord cashRecord=new CashRecord();
        cashRecord.setUser(user);
        cashRecord.setTitle("余额提现(失败)");
        cashRecord.setOrderType(3);//配送订单
        cashRecord.setRecoedType(2);//提现
        if(sellerWithdraw.getWithdrawType()==1){
       //     cashRecord.setMoneyType(1);
            cashRecord.setPayType(1);//余额支付
        }else  if(sellerWithdraw.getWithdrawType()==2){
      //      cashRecord.setMoneyType(2);
            cashRecord.setPayType(4);//押金支付
        }
        cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
        cashRecord.setMoney(sellerWithdraw.getDrawPrice());
        cashRecord.setStatus(null);//提现
        if(user.getUserType()==2){
            cashRecord.setGivePerson(0);
            cashRecord.setReceivePerson(2);
        }else if(user.getUserType()==3){
            cashRecord.setGivePerson(0);
            cashRecord.setReceivePerson(1);
        }
        cashRecord.setWithdrawStatus(3);//提现失败
        cashRecord.setBankCard(withdrawMesg.getBankNum()); //银行卡号
        cashRecord.setBankName(withdrawMesg.getBankName());//开户行
        cashRecord.setBankCardName(withdrawMesg.getRealName());//持卡人姓名
        cashRecordDao.save(cashRecord);

        //-----------------------钱包余额记录-------------
        CashRecord cashRecord2=new CashRecord();
        cashRecord2.setUser(user);
        cashRecord2.setTitle("余额提现(失败)");
        cashRecord2.setOrderType(3);//配送订单
   //     cashRecord2.setRecoedType(2);//提现
        if(sellerWithdraw.getWithdrawType()==1){
            cashRecord2.setMoneyType(1);
            cashRecord2.setPayType(1);//余额支付
        }else  if(sellerWithdraw.getWithdrawType()==2){
            cashRecord2.setMoneyType(2);
            cashRecord2.setPayType(4);//押金支付
        }
        cashRecord2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
        cashRecord2.setMoney(sellerWithdraw.getDrawPrice());
        cashRecord2.setRecoedType(4);
        cashRecord2.setStatus(null);//提现
        if(user.getUserType()==2){
            cashRecord2.setGivePerson(0);
            cashRecord2.setReceivePerson(2);
        }else if(user.getUserType()==3){
            cashRecord2.setGivePerson(0);
            cashRecord2.setReceivePerson(1);
        }
        cashRecordDao.save(cashRecord2);
        sellerWithdraw.setStatus(3);
        sellerWithdrawDao.save(sellerWithdraw);
        return JsonResp.ok();
    }

    /**
     * @删除-one(永久)
     * @param sellerWithdrawId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSellerWithdrawOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSellerWithdrawOne(Long sellerWithdrawId) {
        log.debug("删除-one(永久)");
        sellerWithdrawDao.delete(sellerWithdrawId);
        return JsonResp.ok();
    }

    /**
     * @批量删除(永久)
     * @param sellerWithdraws
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeSellerWithdraw",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeSellerWithdraw(@RequestBody List<SellerWithdraw> sellerWithdraws) {
        log.debug("批量删除(永久)");
        sellerWithdrawDao.delete(sellerWithdraws);
        return JsonResp.ok();
    }

    /**
     * 提现验证码验证
     * @return JsonResp
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/checkCode",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp checkCode(String phone, String code,Integer userType) throws UnsupportedEncodingException {
        log.debug("提现验证码验证");
        try {
            Boolean aBoolean = SmsUtils.checkCode(phone, code, userType);
            if(!aBoolean){
                throw new FailException("验证码错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResp.ok();
    }


    /**
     * @商家或骑手提现
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/withdraw",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp withdraw(Long userId,Long drawId,Double drawPrice,Integer type) {
        log.debug("商家或骑手提现");
        WithdrawSetting withdrawSetting=withdrawSettingDao.findByStatus(0);
        String startTime=withdrawSetting.getStartTime();
        String endTime=withdrawSetting.getEndTime();
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder stringBuStartTime=new StringBuilder();
        stringBuStartTime.append(sf.format(new Date()).substring(0,8));//截取yyyy-MM-
        stringBuStartTime.append(startTime.substring(0,2));//截取dd
        stringBuStartTime.append(" ");
        stringBuStartTime.append(startTime.substring(3,startTime.length()));//截取HH:mm:ss
        StringBuilder stringBuEndTime=new StringBuilder();
        stringBuEndTime.append(sf.format(new Date()).substring(0,8));//截取yyyy-MM
        stringBuEndTime.append(endTime.substring(0,2));//截取dd
        stringBuEndTime.append(" ");
        stringBuEndTime.append(endTime.substring(3,endTime.length()));//截取HH:mm:ss
        try {
            Long currnetTime=sf.parse(sf.format(new Date())).getTime();
            Long startTime2=sf.parse(stringBuStartTime.toString()).getTime();
            Long endTime2=sf.parse(stringBuEndTime.toString()).getTime();
            if(currnetTime>=startTime2 && currnetTime<=endTime2){
                User user=userDao.findOne(userId);
                Account account=accountDao.findByUser(user);
                if(account.getAllMoney().compareTo(drawPrice)<0){
                    return  JsonResp.fa("余额不足，无法提现");
                }
                WithdrawMesg withdrawMesg=withdrawMesgDao.findOne(drawId);
                SellerWithdraw sellerWithdraw=new SellerWithdraw();
                sellerWithdraw.setUser(user);
                sellerWithdraw.setWithdrawMesg(withdrawMesg);
                sellerWithdraw.setDrawPrice(drawPrice);
                sellerWithdraw.setCommissionPrice(0.00);//本次手续费
                sellerWithdraw.setStatus(1);
                sellerWithdraw.setWithdrawPoundage(0.00);//提现手续费
                sellerWithdraw.setSellerPrice(drawPrice);
                sellerWithdraw.setWithdrawType(type);
                sellerWithdrawDao.save(sellerWithdraw);
        //--------------------------余额扣钱----------------------
                account.setAllMoney(new BigDecimal(String.valueOf(account.getAllMoney())).subtract(new BigDecimal(String.valueOf(drawPrice))).doubleValue());
                accountDao.save(account);
        //--------------------------钱包 余额记录----------------------
                CashRecord cashRecord2=new CashRecord();
                cashRecord2.setUser(user);
                cashRecord2.setTitle("余额提现");
                cashRecord2.setOrderType(3);//配送订单
                 cashRecord2.setRecoedType(3);//提现
                if(sellerWithdraw.getWithdrawType()==1){
                    cashRecord2.setMoneyType(1);
                    cashRecord2.setPayType(1);//余额支付
                }else  if(sellerWithdraw.getWithdrawType()==2){
                    cashRecord2.setMoneyType(2);
                    cashRecord2.setPayType(4);//押金支付
                }
                cashRecord2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecord2.setMoney(-drawPrice);
                cashRecord2.setStatus(1);//提现
                if(user.getUserType()==2){
                    cashRecord2.setGivePerson(0);
                    cashRecord2.setReceivePerson(2);
                }else if(user.getUserType()==3){
                    cashRecord2.setGivePerson(0);
                    cashRecord2.setReceivePerson(1);
                }
                cashRecordDao.save(cashRecord2);

        //--------------------------钱包明细- 提现记录---------------------
                CashRecord cashRecord = new CashRecord();
                cashRecord.setUser(user);
                String title="余额提现";
                cashRecord.setTitle(title);
                cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecord.setOrderType(3);//1表示配送订单，2表示商城订单，3表示其他
              //  cashRecord.setOrderNumber(orderGoods.getOrderNumber());//订单编码
                cashRecord.setRecoedType(2);//流水类型，1表示充值，2表示提现，3表示消费扣钱
                cashRecord.setMoney(-drawPrice);
              //  cashRecord.setMoneyType(1);//余额
                cashRecord.setPayType(1);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                cashRecord.setBankName(withdrawMesg.getBankName());//银行名称
                cashRecord.setBankCardName(withdrawMesg.getRealName());
                cashRecord.setBankCard(withdrawMesg.getBankNum());
                cashRecord.setWithdrawStatus(1);//提现申请中
                if(user.getUserType()==2){
                    cashRecord.setGivePerson(2);
                    cashRecord.setReceivePerson(2);
                }else if(user.getUserType()==3){
                    cashRecord.setGivePerson(1);
                    cashRecord.setReceivePerson(1);
                }
                cashRecord.setStatus(1);
                cashRecordDao.save(cashRecord);//保存支付记录
            }else {
                return  JsonResp.fa("当前时间不在提现时间内！");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return JsonResp.ok();
    }


}
